import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/home.vue';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import axios from 'axios';

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: '/dashboard',
    },
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            {
                path: '/dashboard',
                name: 'dashboard',
                meta: {
                    title: '系统首页',
                    requiresAuth: true,
                },
                component: () => import(/* webpackChunkName: "dashboard" */ '../views/dashboard.vue'),
            },
            {
                path: '/system-files',
                name: 'system-files',
                meta: {
                    title: '文件级定位',
                    permiss: '2',
                    requiresAuth: true
                },
                component: () => import(/* webpackChunkName: "system-role" */ '../views/system/file.vue'),
            },

            {
                path: '/system-sentences',
                name: 'system-sentences',
                meta: {
                    title: '语句级定位',
                    permiss: '3',
                    requiresAuth: true
                },
                component: () => import(/* webpackChunkName: "system-role" */ '../views/system/sentence.vue'),
            },

            {
                path: '/system-history',
                name: 'system-history',
                meta: {
                    title: '历史记录',
                    permiss: '4',
                    requiresAuth: true
                },
                component: () => import(/* webpackChunkName: "system-role" */ '../views/system/history.vue'),
            },

            {
                path: '/ucenter',
                name: 'ucenter',
                meta: {
                    title: '个人中心',
                },
                component: () => import(/* webpackChunkName: "ucenter" */ '../views/pages/ucenter.vue'),
            },
            {
                path: '/upload',
                name: 'upload',
                meta: {
                    title: '上传',
                    permiss: '22',
                },
                component: () => import(/* webpackChunkName: "upload" */ '../views/element/upload.vue'),
            },
        ],
    },
    {
        path: '/login',
        meta: {
            title: '登录',
            noAuth: true,
        },
        component: () => import(/* webpackChunkName: "login" */ '../views/pages/login.vue'),
    },
    {
        path: '/register',
        meta: {
            title: '注册',
            noAuth: true,
        },
        component: () => import(/* webpackChunkName: "register" */ '../views/pages/register.vue'),
    },
    {
        path: '/reset-pwd',
        meta: {
            title: '重置密码',
            noAuth: true,
        },
        component: () => import(/* webpackChunkName: "reset-pwd" */ '../views/pages/reset-pwd.vue'),
    },
    {
        path: '/403',
        meta: {
            title: '没有权限',
            noAuth: true,
        },
        component: () => import(/* webpackChunkName: "403" */ '../views/pages/403.vue'),
    },
    {
        path: '/404',
        meta: {
            title: '找不到页面',
            noAuth: true,
        },
        component: () => import(/* webpackChunkName: "404" */ '../views/pages/404.vue'),
    },
    { path: '/:path(.*)', redirect: '/404' },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

const verifyUrl = import.meta.env.VITE_API_URL + '/verify-token';

// 路由守卫
router.beforeEach((to, from, next) => {
  // 如果目标页面需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const token = localStorage.getItem('access_token');
    if (!token) {
        localStorage.clear();
        next('/login');
    } // 发送一个验证 token 的请求
    axios.get(verifyUrl, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => {
      // Token 验证成功，放行
        console.log(response.data.message)
      next();
    })
    .catch(error => {
      if (error.response && error.response.status === 401) {
        // 如果后端返回 token 过期，清除 token，跳转到登录页
        localStorage.removeItem('access_token');
        next({ name: 'login' });
      } else {
        // 如果是其他错误，直接跳转到错误页面或提示
        console.error('Token verification failed:', error);
        next({ name: 'login' });
      }
    });
  } else {
    next();  // 如果不需要认证，直接放行
  }
});

router.afterEach(() => {
    NProgress.done();
});

export default router;
